//
//  HttpConnect.m
//  HandPay
//
//  Created by xy on 10-3-19.
//  Copyright 2010 HANDPAY. All rights reserved.
//

#import "HttpConnect.h"
#import "Utility.h"
#import "ZZTongDefine.h"
#import "ZZTongDefine.h"

#define MAXTIME 60

@implementation HttpConnect
@synthesize receiveHeaders;
@synthesize receiveData;
@synthesize errorCode;

#define TWITTERFON_FORM_BOUNDARY  @"--AaB03x"
-(void)enableConnection{
    if (connect) {
        LOG(@"net req time out");
        self.errorCode = 6;
        [connect cancel];
        [connect release];
        connect = nil;
        finished = YES;
    }
}
-(BOOL)connectImg:(NSString *)url req:(NSDictionary *)params headers:(NSDictionary *)headers{
    if (!url || [url length] == 0) {
        return NO;
    }
    LOG(@"connectWithdata url:%@",url);
    NSRange range = [url rangeOfString:@"zztUploadPicInfo.do"];
    if (range.length == 0) {
        LOG(@"connectWithdata param:%@",params);
    }
   
    
    finished = NO;
    self.receiveData = nil;
    
    
    NSString *MPboundary=[TWITTERFON_FORM_BOUNDARY stringByAppendingString:[Utility getNowDateTime]];

    NSData* data =(NSData*)[params objectForKey:@"pic"];
 
    NSMutableString *body=[[NSMutableString alloc]init];
    NSArray *keys= [params allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"pic"])
        {
            [body appendFormat:@"%@\r\n",MPboundary];
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
        }
    }
    
    [body appendFormat:@"%@\r\n",MPboundary];
    
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"byte\"\r\n"];

    [body appendFormat:@"Content-Type: application/octet-stream\r\n\r\n"];
    
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@--",MPboundary];
   
    NSMutableData *myRequestData=[NSMutableData data];
    
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    [body release];
    [myRequestData appendData:data];
    
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    [end release];
    
    
	NSMutableURLRequest * requestm = [[NSMutableURLRequest alloc] init];
    
	[requestm setURL:[NSURL URLWithString:url]];
	[requestm setHTTPMethod:@"POST"];
    
    if (myRequestData && [myRequestData length] > 0) {
        [requestm setHTTPBody:myRequestData];
    }
    
    
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",[MPboundary substringFromIndex:2]];
    [headers setValue:content forKey:@"Content-Type"];
    [content release];
    [headers setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forKey:@"Content-Length"];

    if (headers && [headers count] > 0) {
        [requestm setAllHTTPHeaderFields:headers];
    }
    
    connect = [[NSURLConnection alloc] initWithRequest:requestm delegate:self];
    [connect start];
    [requestm release];
    
    [NSTimer scheduledTimerWithTimeInterval:MAXTIME target:self selector:@selector(enableConnection) userInfo:nil repeats:NO];
    
    while(!finished) {
		[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
	}
    
    if (self.errorCode != 0) {
        return NO;
    }
    
    if (!self.receiveData || [self.receiveData length] == 0) {
        self.receiveData = nil;
    }
    else
    {
        LOG(@"response:%@",[NSString stringWithUTF8String:[self.receiveData bytes]]);
    }
    
    return YES;

}
-(BOOL)connect:(NSString*)url req:(NSString*)param headers:(NSDictionary*)headers{
    if (!url || [url length] == 0) {
        return NO;
    }
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc]init];
    LOG(@"connectWithdata url:%@",url);
    NSRange range = [url rangeOfString:@"zztUploadPicInfo.do"];
    if (range.length == 0) {
        LOG(@"connectWithdata param:%@",param);
    }
    [pool release];
    
    finished = NO;
    self.receiveData = nil;
    
	NSMutableURLRequest * requestm = [[NSMutableURLRequest alloc] init];
    
	[requestm setURL:[NSURL URLWithString:url]];
	[requestm setHTTPMethod:@"POST"];
    
    if (param && [param length] > 0) {
        NSData * postData=[param dataUsingEncoding:NSUTF8StringEncoding];
        [requestm setHTTPBody:postData];
    }
    
    if (headers && [headers count] > 0) {
        [requestm setAllHTTPHeaderFields:headers];        
    }
   
    connect = [[NSURLConnection alloc] initWithRequest:requestm delegate:self];
    [connect start];
    [requestm release];
    
    [NSTimer scheduledTimerWithTimeInterval:MAXTIME target:self selector:@selector(enableConnection) userInfo:nil repeats:NO];
    
    while(!finished) {
		[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
	}
    
    if (self.errorCode != 0) {
        return NO;
    }
    
    if (!self.receiveData || [self.receiveData length] == 0) {
        self.receiveData = nil;
    }
    else
    {
        LOG(@"response:%@",[NSString stringWithUTF8String:[self.receiveData bytes]]);
    }
    
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
    NSHTTPURLResponse* rsp = (NSHTTPURLResponse*)response;
    if (!rsp) {
        self.errorCode = 8;
        finished = YES;
        return;
    }
    
    self.errorCode = [rsp statusCode];
    if (self.errorCode != 200) {
        finished = YES;
        return;
    }
    self.errorCode = 0;
    self.receiveHeaders = [rsp allHeaderFields];
    
    NSMutableData* tempData = [[NSMutableData alloc] init];
    self.receiveData = tempData;
    [tempData release];
    [self.receiveData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (finished) {
        return;
    }
    
    [self.receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [connect release];
    connect = nil;
	finished = YES;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	if (finished) {
        return;
    }
    
    self.errorCode = 1;
    [connect release];
    connect = nil;
    finished = YES;
}


- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (void)dealloc {    
//    self.receiveData = nil;
//    self.receiveHeaders = nil;
    
    [super dealloc];
}
@end
